package com.herench.bunch.emr.convert;

import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v24.datatype.MA;
import ca.uhn.hl7v2.model.v24.group.ADT_A01_INSURANCE;
import ca.uhn.hl7v2.model.v24.message.ADT_A01;
import ca.uhn.hl7v2.model.v24.message.QBP_Q11;
import ca.uhn.hl7v2.model.v24.message.QRY_Q01;
import ca.uhn.hl7v2.model.v24.segment.*;
import com.herench.bunch.commons.support.RequestMessage;
import com.herench.bunch.commons.utils.IdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MedicalFreeConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Map<String, Object> doToMessage(RequestMessage requestMessage) throws Exception {
        Map<String, Object> params = new HashMap<>();
        QRY_Q01 hl7Message = (QRY_Q01) requestMessage.getHl7Message();
        QRD qrd = hl7Message.getQRD();
        String inpNo = qrd.getQrd4_QueryID().getValue();
        String visitId = qrd.getQrd3_QueryPriority().getValue();
        params.put("inpNo", inpNo);
        params.put("visitId",visitId);
        return params;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Message fromMessage(Object message) throws Exception {
        Assert.notNull(message, "message 为空.");
        List<Map<String, Object>> resList = (List<Map<String, Object>>) message;
        ADT_A01 adtA01 = new ADT_A01();
        adtA01.initQuickstart("ADT_A01", "ADT_A01", "A");
        MSH msh = adtA01.getMSH();
        initResponseMessageMSH(msh);
        StringBuffer buffer = new StringBuffer();
        String fee = null;
        for (Map<String,Object> reqMap : resList){
            if (reqMap.get("fee") == null || reqMap.get("fee") == "null"){
                fee = "";
            }else {
                fee = String.valueOf(reqMap.get("fee"));
            }
            buffer.append(reqMap.get("custItemName")).append("=").append(fee).append("#");
        }
        String buf = buffer.toString();
        String res = buf.substring(0,buf.length()-1);
        PID pid = adtA01.getPID();
        pid.getPid1_SetIDPID().setValue(res);
        return adtA01;

    }

    @Override
    public Message generatorReqMessage() throws Exception {
        QBP_Q11 qbp = new QBP_Q11();
        qbp.initQuickstart("QBP_Q11", "Q11", "L");
        MSH msh = qbp.getMSH();
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("SSM");
        msh.getMessageControlID().setValue(IdGenerator.getUUID());
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("200140");
        msh.getMsh11_ProcessingID().getProcessingMode().setValue("QR");
        QPD qpd = qbp.getQPD();
        qpd.getMessageQueryName().getIdentifier().setValue("查询号别");
        qpd.getQpd2_QueryTag().setValue("QR");
        return qbp;
    }
}
